
<template>
<view class="index">
	<cover-view class="banner-ad">
		<ad unit-id="adunit-4e51882b037237c7"></ad>
	</cover-view>
	<!-- 地图部分 -->
	<view class="map">
		<map id="myMap" style="width: 100%; height: 100%;" :markers="map.markers" :latitude="map.center[1]" :longitude="map.center[0]" 
			@regionchange="regionchange" show-location	@markertap="markertap" @tap="tap"></map>
	</view>
	
	<!-- <cover-image src="/static/indexZhaoshangBtn.png" class="zhaoshangBtn" @tap="callKefu"></cover-image> -->
	
	<cover-view class="bottom">
		<cover-view style="width: 100%; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center;">
			<cover-image @tap="toshoplist" style="width: 96upx; height: 82upx; margin-left: 20upx;" src="../../static/local.png"></cover-image>
			<cover-image @tap="scanCode" style="width: 400upx; height: 150upx;" src="../../static/indexSubmit.png"></cover-image>
			<cover-image @tap="toPerson" style="width: 98upx; height: 82upx; margin-right: 20upx;" src="../../static/person.png"></cover-image>
		</cover-view>
	</cover-view>
	
	<cover-image src="/static/came.png" class="cameBtn"></cover-image>
	<cover-image src="/static/indexCenterBtn.png" class="centerBtn" @tap="movelocation"></cover-image>
	<cover-image src="/static/indexFindBtn.png" class="findBtn" @tap="selePosition"></cover-image>
	<cover-image src="/static/vip.png" class="vipBtn" @tap="turnTo( 'huiyuan' )"></cover-image>
	<cover-image src="/static/indexHelpBtn.png" class="helpBtn" @tap="turnTo( 'help' )"></cover-image>
	<!-- <cover-view class="helpBtn">
		<button open-type="contact">
			<cover-image src="/static/indexHelpBtn.png"></cover-image>
		</button>
	</cover-view> -->
	
	<!-- <cover-view v-if="authBlank" style="height: 100%; width: 100%; position: absolute; left: 0; top: 0; z-index: 100; background: rgba(0, 0, 0, 0.2);">
		<cover-view style="height: 480upx; width: 100%; background: #fff; position: absolute; left: 0; bottom: 0; z-index: 101;
			border-radius: 30upx 30upx 0upx 0upx; box-shadow: 0upx -3upx 10upx 0upx rgba(241, 243, 245, 0.54);">			
			<cover-image style="width: 568upx; height: 188upx; position: absolute; z-index: 101; left: 30upx; top: 60upx;" src="/static/login.png"></cover-image>
			<button lang="zh_CN" @click="authInfo" style="width: 690upx; height: 90upx; line-height: 90upx; background: #EF7738;
				box-shadow: 0upx 3upx 17upx 1upx rgba(239, 146, 98, 0.33); border-radius: 45upx; color: #fff; font-size: 30upx; text-align: center; position: absolute;
				left: 30upx; bottom: 80upx; z-index: 101;">授权昵称/头像</button>
			<cover-view style="text-align: center; font-size: 26upx; color: #666; line-height: 2; position: absolute; z-index: 101; left: 0; bottom: 15upx; 
				text-decoration: underline; width: 100%;" @click="authBlank = false">暂不登录</cover-view>
		</cover-view>
	</cover-view> -->
	
	<cover-view v-if="phoneBlank" style="height: 100%; width: 100%; position: absolute; left: 0; top: 0; z-index: 100; background: rgba(0, 0, 0, 0.2);">
		<cover-view style="height: 480upx; width: 100%; background: #fff; position: absolute; left: 0; bottom: 0; z-index: 101;
			border-radius: 30upx 30upx 0upx 0upx; box-shadow: 0upx -3upx 10upx 0upx rgba(241, 243, 245, 0.54);">			
			<cover-image style="width: 568upx; height: 188upx; position: absolute; z-index: 101; left: 30upx; top: 60upx;" src="/static/phone.png"></cover-image>
			<button open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="authPhone" style="width: 690upx; height: 90upx; line-height: 90upx; background: #EF7738;
				box-shadow: 0upx 3upx 17upx 1upx rgba(239, 146, 98, 0.33); border-radius: 45upx; color: #fff; font-size: 30upx; text-align: center; position: absolute;
				left: 30upx; bottom: 80upx; z-index: 101;">绑定手机号</button>
			<cover-view style="text-align: center; font-size: 26upx; color: #666; line-height: 2; position: absolute; z-index: 101; left: 0; bottom: 15upx; 
				text-decoration: underline; width: 100%;" @click="phoneBlank = false">暂不授权</cover-view>
		</cover-view>
	</cover-view>
	
	<cover-view class="bus-detail" v-if="shop.blank" @tap="turnToShop">		
		<cover-view class="topItem">
			<cover-image :src="shop.info.shopPhotUrl || '/static/logo.png'" style="width: 130upx; height: 130upx;"></cover-image>
			<cover-view class="topRight">
				<cover-view class="topRightFlex">
					<cover-view style="font-size: 33upx; color: #122a2a; font-weight: 600;">{{ shop.info.shopName || '无' }}</cover-view>
					<cover-view style="font-size: 18upx; color: #768181;">{{ shop.info.lang || 0 }}</cover-view>
				</cover-view>
				<cover-view style="font-size: 20upx; color: #b4bdbe; width: 100%;">{{ shop.info.shopSite || '无' }}</cover-view>
				<cover-view style="font-size: 24upx; color: #455354; height: 36upx; line-height: 36upx; width: 100%;">营业时间:{{ shop.info.shopHours || '无' }}</cover-view>
			</cover-view>
		</cover-view>
		<cover-view style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center;">
			<cover-view style="font-size: 20upx; color: #455354; margin-left: 22upx;">{{ shop.info.ifBorrow !== 0 ? '不' : '' }}可租借</cover-view>
			<cover-view style="font-size: 20upx; color: #455354; margin-left: 22upx;">{{ shop.info.ifReturn !== 0 ? '不' : '' }}可归还</cover-view>
		</cover-view>
	</cover-view>
	
</view>
</template>


<script>
import { HTTP } from '../../http.js'
let http = new HTTP;
let height = 30;
let padding = 10;
let EARTH_RADIUS = 6378137.0;
export default {
	data() {
		return {
			// 窗口宽度 动态获取 用来设置商铺小图标的大小
			windowWidth: 320,
			// 用户信息部分
			userInfo:{
				// 用户的头像 昵称等信息 这个信息是从微信端获取的 本页面只需要头像
				info: { avatarUrl: '/static/user.png' },
				// 用户信息 电小童后台获取
				sysinfo: {},
				getToken: (code,info,cb)=>{	
					http.request({
						url: `login/wx?js_code=${ code }&avatarUrl=${ encodeURIComponent(info.avatarUrl) }&city=${ info.city || '' }&country=${ info.country || '' }&language=${ info.language || '' }&`+
						 `province=${ info.province || '' }&nickName=${ encodeURIComponent(info.nickName) }&gender=${ info.gender||'' }`,
						method: 'post',
						success: (res)=>uni.setStorage({ key: 'user', data: res.dataList, 
							success: ()=>{
								this.userInfo.sysinfo = res.dataList;	
								if(cb) cb();
							} 
						})
					});	
				},
				getUserLocation: () => {
					// 用户位置初始化程序
					uni.getLocation({ 
						type: 'wgs84',
						success: (res) => {
							// 获取初始点附近的
							this.userInfo.getMarkers(res.longitude, res.latitude);
							this.map.center=[ res.longitude, res.latitude ];
							this.map.position=[ res.longitude, res.latitude ];
						},
						fail: (err) => {
							let res = { longitude: 108.93984, latitude: 34.34127 };
							this.userInfo.getMarkers(res.longitude, res.latitude);
							this.map.center=[ res.longitude, res.latitude ];
							this.map.position=[ res.longitude, res.latitude ];
						}
					});
				},
				// 获取初始点的shop
				getMarkers: (longitude, latitude) => {
					// 判断 经度 和 维度 是否存在
					if(longitude && latitude){
						http.request({
							url: `ShopManageController/getGraticulesShopList?longitude=${ longitude }&latitude=${ latitude }`,
							method: 'get',
							success: (res)=>{								
								let arr = res.dataList || [];
								// 防止商店获取到后消失
								if(arr.length == 0) return;
								this.map.markers = arr.map(v => {
									// 在shop上记录每一个商铺id对应的商铺的信息 点击图标时能快速的展示商店的信息
									if(!this.shop.markerJson[ v.shopId ]) this.shop.markerJson[ v.shopId ] = JSON.parse(JSON.stringify( v ));
									if (v.vipStatus == 1) {
										return { id: v.shopId, ...v, iconPath: '/static/vip.png', width: this.windowWidth * 0.1, height: this.windowWidth * 0.11 };
									} else {
										return { id: v.shopId, ...v, iconPath: '/static/icon.png', width: this.windowWidth * 0.1, height: this.windowWidth * 0.11 };
									}
								});
							}
						});
					}
				},
			},
			map: {
				// 地图中心点
				center: [],
				// 记录用户所在位置 用于计算商店和用户间的距离
				position: [],
				// 地图对象
				object: null,
				// 商店列表
				markers: [],
				// 地图建立 
				init: () => { this.map.object = uni.createMapContext('myMap'); },
				// 地图移动时获取周围的商店
				getShoplist: (longitude, latitude) => {
					if(longitude && latitude){			
						http.request({
							url: `ShopManageController/getGraticulesShopList?longitude=${longitude}&latitude=${latitude}`,
							method: 'get',
							success: (res) => {			
								let arr = res.dataList || [];
								// 防止商店获取到后消失
								if(arr.length == 0) return;
								this.map.markers=arr.map(v => {
									// 在shop上记录每一个商铺id对应的商铺的信息 点击图标时能快速的展示商店的信息
									if(!this.shop.markerJson[ v.shopId ]) this.shop.markerJson[ v.shopId ] = JSON.parse(JSON.stringify( v ));
									return { id: v.shopId, ...v, iconPath: '/static/icon.png', width: this.windowWidth * 0.1, height: this.windowWidth * 0.11 };
								});
							}
						});
					}	
				}
			},
			shop: {
				blank: false,
				info: {},
				markerJson: {},
				getInfo: (id) => {
					let lang;
					this.map.markers.forEach(ele=>{
						if(ele.id == id){  
							lang = this.getFlatternDistance( this.map.position[1], this.map.position[0], ele.latitude, ele.longitude );
							// 选中商店图标高亮
							ele.height = this.windowWidth * 0.143; 
							ele.width = this.windowWidth * 0.13; 
							ele.callout = { content: lang, padding: 6, borderRadius: 5, bgColor: '#000', color: '#fff' }; 
						} else { 
							// 其他商店图标取消高亮
							ele.height = this.windowWidth * 0.11; 
							ele.width = this.windowWidth * 0.1; 
						}
					})
					if(this.shop.markerJson[ id ].shopName){
						// 判断商店信息完整的话 直接展示商店信息
						this.shop.info = { ...this.shop.markerJson[id], lang };		
						this.shop.blank = true;				
					}else{
						// 判断商店信息不完整 从服务器获取商店信息 并记录在本地
						http.request({
							url: `ShopManageController/getShopManage?shopId=${id}`,
							method: 'get',
							success: (res) => {		
								let json = res.dataList || {};
								this.shop.markerJson[ id ] = json;
								let info = JSON.parse(JSON.stringify( json ));
								this.shop.info = { ...info, lang };
								this.shop.blank = true;
							}
						});						
					}
				},
				close: () => {
					// 隐藏展示的商店信息 并清空
					this.shop.blank = false;
					this.shop.info = {};
				},
				shopClick: () => {
					// 点击查看商店的详细信息
					uni.navigateTo({ url: `shop?id=${ this.shop.info.shopId }` });
				}
			},
			// 用户授权版面
			authBlank: false,
			// 用户手机号版面
			phoneBlank: false,
			isNewUser: false,
			routeInfo: null,
			pageAD: null,
			initAD: true
		}
	},
	methods: {
		authInfo() {				
			wx.getUserProfile({
				desc: '用于完善用户信息资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (infoRes) => {
					this.userInfo.info = infoRes.userInfo;
					uni.login({ 
						provider: 'weixin', 
						success: (res) => { 
							this.isNewUser = false;
							this.userInfo.getToken(res.code, this.userInfo.info, () => {
								if (this.routeInfo) {
									this.mount(this.routeInfo);
								}
							}) 
						} 
					});
					this.authBlank = false;
				}
			})
		},
		authPhone(e) {
			let sessionKey = this.userInfo.sysinfo.sessionKey;
			let encryptedData = e.detail.encryptedData, iv = e.detail.iv;
			if (!encryptedData || !iv) {
				return ;
			}
			http.request({
				url: `login/decodeWxPhone?sessionKey=${ encodeURIComponent(sessionKey) }&encryptedData=${ encodeURIComponent(encryptedData) }&iv=${ encodeURIComponent(iv) }`,
				method: 'get',
				success: (res) => {
					this.userInfo.sysinfo.phone = res.dataList.phoneNumber;
					uni.setStorage({ key: 'user', data: this.userInfo.sysinfo });
					this.phoneBlank = false;
				}
			});
		},
		toshoplist() {
			// 跳转到附近商铺
			this.shifouzhuce(() => this.turnTo( 'shoplist' ), () => this.turnTo( 'getmes?cb=shoplist' ));
		},
		toPerson() {
			// 跳到个人中心
			this.shifouzhuce(() => uni.navigateTo({ url: 'person' }), () => uni.navigateTo({ url: 'getmes?cb=toPerson' }));
		},		
		scanCode() {
			// 扫码充电
			this.shifouzhuce(
				// 扫码前先查后台是不是有未完成的订单 （未支付 或 为归还） 
				() => this.getRight(
					() => uni.scanCode({ onlyFromCamera: true, success: (res) => { let str = res.result || ''; this.jiexichongdian( str ); } })
				),
				()=>uni.navigateTo({ url: 'getmes?cb=scanCode' })
			);
		},
		jiexichongdian(str,init) {
			// 解析二维码 把这个给变简单了
			let id;
			if(str.indexOf( 'dianxiaotong' ) > 0) id = str.split( '=' )[1];
			if( id ) uni.navigateTo({ url: 'device?id=' + id });
			else if( !init ) uni.showModal({ content: "请扫描正确的二维码，该二维码非本系统设备！", showCancel: false }); 
		},
		getRight(cb){	
			// 查看用户是否有未完成订单
			uni.showLoading({ title: '加载中' });
			http.request({
				url: `orderFormController/notPayOrder?userId=${ this.userInfo.sysinfo.userId }`,
				method: 'get',
				success: (res) => {			
					uni.hideLoading();
					if(res.dataList && res.dataList.orderId){
						let orderId = res.dataList.orderId;
						uni.showModal({ title: '提示', content: '检测到尚有订单未完成，是否立即查看该订单详情！',
							success: (res) => { if(res.confirm) uni.navigateTo({ url: 'dingdanxiangqing?id='+orderId }); }
						});
					}else if(cb) cb();
				},
				fail: () => { uni.hideLoading(); }
			});	
		},
		regionchange(e) {
			// 用户滑动地图
			this.shop.close();
			if(e.type === 'end') this.map.object.getCenterLocation({ success: (res) => { this.map.getShoplist(res.longitude, res.latitude); }});
		},
		// 关闭地图上的商户信息
		tap(e){ this.shop.close(); },
		callKefu(){ uni.makePhoneCall({ phoneNumber: '400-003-9881' }); },
		markertap(e){ this.shop.getInfo(e.markerId) },
		getRad(d){ let PI = Math.PI; return d*PI/180.0; },
		getFlatternDistance(lat1, lng1, lat2, lng2){
			var radLat1 = this.getRad( lat1 );
			var radLat2 = this.getRad( lat2 );
			var a = radLat1 - radLat2;
			var b = this.getRad( lng1 ) - this.getRad( lng2 );
			var s = 2 * Math.asin( Math.sqrt( Math.pow( Math.sin( a / 2 ), 2 ) + Math.cos( radLat1 ) * Math.cos( radLat2 ) * Math.pow( Math.sin( b / 2 ), 2 ) ) );
			s = s * EARTH_RADIUS;
			s = Math.round( s * 10000 ) / 10000.0;
			s = Math.floor( s );
			if( s > 1000 ) s = Math.round( s / 1000 * 100 ) / 100 + 'km';
			else s = s + 'm';
			return s;
		},
		// 地图选点
		selePosition(){
			uni.chooseLocation({ success: (res) => { this.map.center = [ res.longitude, res.latitude ]; } });
		},
		shifouzhuce(cb, err){
			if (this.isNewUser) {  
				this.authBlank = true;
			} else {	
				cb();
			}
		},	
		movelocation() { 
			if(this.map.object){ this.map.object.moveToLocation(); }
			else setTimeout(()=>{ this.movelocation(); },300);
		},		
		turnTo(name) { uni.navigateTo({ url: name }); },
		turnToShop() {
			uni.navigateTo({ url: 'shop?id=' + this.shop.info.shopId });		
		},
		mount(e){
			if(e.cb&&e.cb=='toPerson'){ this.toPerson(); return ; }
			if(e.cb&&e.cb=='scanCode'){ this.scanCode(); return ; }
			if(e.cb&&e.cb=='shoplist'){ this.toshoplist(); return ; }
			if(e.cb&&e.cb=='qianbao'){ 
				this.shifouzhuce(()=>this.turnTo('wallet'),()=>this.turnTo('getmes?cb=qianbao'));
				return ; 
			}
			let str='';
			if(e.q){ str = e.q; }
			if(str){ 
				if(str.indexOf('%3D')>-1){
					let id=str.split('%3D')[1];
					this.getRight(()=>this.jiexichongdian('https://qr.dianxiaotong.net?='+id,true))
				}else if(str.indexOf('=')>-1){
					let id=str.split('=')[1];
					this.getRight(()=>this.jiexichongdian('https://qr.dianxiaotong.net?='+id,true))
				}else{
					this.getRight(() => this.jiexichongdian(str, true));												
				}											
			}else{
			}
		},
		createAD() {
			if (wx && wx.createInterstitialAd) {
				let interstitialAd = this.pageAD = wx.createInterstitialAd({ adUnitId: 'adunit-7d98ee4f11ad2239' });
				interstitialAd.onLoad((e) => { console.log(e, '广告加载'); });
				interstitialAd.onError((e) => { console.log(e, '广告失败'); });
				interstitialAd.onClose(() => {});
			}
		},
		showAD() {
			if (this.pageAD && this.initAD) {
				this.initAD = false;
				this.pageAD.show().catch((err) => { this.initAD = true; });
			}
		},
		destroyAD() {
			if (this.pageAD) {
				this.pageAD.destroy();
			}
		},
		getVipInfo(userId, token) {
			return new Promise((succ, err) => {
				http.request({
					url: `vip/getUserVipStatus?userId=${ userId }`,
					method: 'get',
					success: (res) => {
						res.dataList.token = token;
						succ(res);
					},
					fail: (res) => {
						succ({});
					}
				}, token);	
			});
		}
	},
	onLoad(e) {
		this.createAD();
		this.showAD();
		
		uni.getSystemInfo({ success: (res) => { this.windowWidth = res.windowWidth; } });
		uni.login({ 
			provider: 'weixin', 
			success: (res) => { 
				http.request({
					url: `login/wxNewUser?js_code=${ res.code }`,
					method: 'get',
					success: (res) => {
						if (res.dataList.isNewUser) {
							this.isNewUser = true;
						} else {
							this.isNewUser = false;
						}		
						if (this.isNewUser) {
							this.routeInfo = e;
							this.authBlank = true;
						} else {
							let sessionKey = res.dataList.sessionKey;
							this.getVipInfo(res.dataList.userId, res.dataList.token).then(res => {
								res.dataList.sessionKey = sessionKey;
								uni.setStorage({ 
									key: 'user', data: res.dataList,
									success: () => {
										this.userInfo.sysinfo = res.dataList;	
										this.mount(e);
									} 
								});	
							});	
						}
						this.map.init();
						this.userInfo.getUserLocation();
					},
				});
			} 
		});
		
	}
}
</script>

<style>
.index {
	text-align: center;
	height: 100vh;
	position: relative;
}

.index .map {
	width: 100%;
	height: 100%;
	position: absolute;
	z-index: 5;
	box-sizing: border-box;
	bottom: 0;
	left: 0;
	padding-bottom: 150upx;
}

.index .zhaoshangBtn {
	width: 606upx;
	height: 170upx;
	border-radius: 10upx;
	z-index: 10;
	position: absolute;
	top: 40upx;
	left: 72upx;
}

.index .bottom {
	width: 100%;
	height: 180upx;
	background: #FFF;
	z-index: 10;
	position: absolute;
	bottom: 0;
	left: 0;	
	box-shadow: 0upx -3upx 10upx 0upx rgba(241, 243, 245, 0.54);
	border-radius: 30upx 30upx 0upx 0upx;
}

.index .centerBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 264upx;
	left: 27upx;	
	border-radius: 50%;
}

.index .findBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 398upx;
	left: 27upx;	
	border-radius: 50%;
}

.index .helpBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 264upx;
	right: 27upx;	
	border-radius: 50%;
}

.index .vipBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 398upx;
	right: 27upx;	
	border-radius: 50%;
}

.index .cameBtn {
	width: 40upx;
	height: 70upx;
	z-index: 50;
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -20upx;
	margin-top: -130upx;
}

.index .bus-detail {
	position: absolute;
	bottom: 190upx;
	left: 40upx;
	width: 670upx; 
	z-index: 60;
	box-sizing: border-box; 
	padding: 30upx 40upx; 
	border: solid 1upx #f2f2f2; 
	background-color: #fff;
	border-radius: 10upx; 
	text-align: left;
	box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.1);
}
.bus-detail .topItem {
	width: 100%;
	height: 180upx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: flex-start;
}
.bus-detail .topRight {
	width: 440upx;
	height: 130upx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;	
}
.bus-detail .topRightFlex {
	width: 100%;
	height: 35upx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;	
}
.index .bus-detail .title {
	padding: 20upx;
	border-bottom: 1px dashed #eee;
}
.index .bus-detail .right {
	display: inline-block;
	margin-left: 20upx;
}
.index .bus-detail .title cover-image {
	display: inline-block;
	width: 150upx;
	height: 150upx;
}
.index .bus-detail .right .name {
	line-height: 60upx;
	font-size: 36upx;
	color: #333;
}
.bus-detail .right .address {
	line-height: 50upx;
	font-size: 26upx;
	color: #bbb;
}
.bus-detail .right .time {
	line-height: 40upx;
	font-size: 26upx;
	color: #777;
}
.bus-detail .status {
	padding: 20upx;
	color: #666;
	font-size: 26upx;
}
.banner-ad {
	width: 100%;
	height: auto;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 10;
}
</style>
